<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="my-houses-content">
      <h1 class="page-title">我的房源</h1>

      <!-- 主内容区域 -->
      <div class="my-houses-area">
          <div class="content-header">
            <h2>我的房产认证</h2>
            <p>管理您的房产认证信息和发布的房源</p>
          </div>

          <!-- 操作按钮区域 -->
          <div class="action-buttons">
            <el-button @click="refreshData" :loading="loading">刷新数据</el-button>
            <el-button
                type="danger"
                @click="batchDelete"
                :disabled="selectedVerifications.length === 0"
                v-if="hasDeleteableItems"
            >
              批量删除 ({{ selectedVerifications.length }})
            </el-button>
          </div>

          <!-- 房产认证列表 -->
          <div class="verifications-section">
            <div class="section-header">
              <h3>房产认证列表</h3>
              <div class="status-filter">
                <el-radio-group v-model="statusFilter" @change="filterByStatus">
                  <el-radio-button :label="null">全部</el-radio-button>
                  <el-radio-button :label="0">待审核</el-radio-button>
                  <el-radio-button :label="1">已通过</el-radio-button>
                  <el-radio-button :label="2">已驳回</el-radio-button>
                  <el-radio-button :label="3">已取消</el-radio-button>
                </el-radio-group>
              </div>
            </div>

            <div class="verifications-container" v-loading="loading">
              <el-table
                  :data="filteredVerificationList"
                  style="width: 100%"
                  stripe
                  @selection-change="handleSelectionChange"
              >
                <el-table-column
                    type="selection"
                    width="55"
                    :selectable="isRowSelectable"
                ></el-table-column>
                <el-table-column prop="propertyVerifyId" label="认证ID" width="100"></el-table-column>
                <el-table-column prop="propertyNo" label="房产证编号" width="180"></el-table-column>
                <el-table-column prop="propertyAddr" label="房产地址" min-width="200"></el-table-column>
                <el-table-column prop="verifyStatus" label="审核状态" width="120">
                  <template #default="scope">
                    <el-tag :type="getStatusTagType(scope.row.verifyStatus)">
                      {{ getStatusText(scope.row.verifyStatus) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="applyTime" label="申请时间" width="180">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.applyTime) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="280">
                  <template #default="scope">
                    <el-button
                        size="small"
                        type="primary"
                        @click="viewVerificationDetail(scope.row)"
                    >
                      查看详情
                    </el-button>
                    <el-button
                        v-if="scope.row.verifyStatus === 2"
                        size="small"
                        type="warning"
                        @click="viewRefuseReason(scope.row)"
                    >
                      查看驳回原因
                    </el-button>
                    <el-button
                        size="small"
                        type="danger"
                        @click="deleteVerification(scope.row)"
                        :disabled="!canDelete(scope.row.verifyStatus)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 空状态 -->
              <div v-if="filteredVerificationList.length === 0 && !loading" class="empty-state">
                <el-empty description="暂无房产认证信息">
                </el-empty>
              </div>

              <!-- 分页 -->
              <div class="pagination-container" v-if="filteredVerificationList.length > 0">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 50]"
                    :total="totalVerifications"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
  </UserLayout>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserLayout from '@/components/layout/UserLayout.vue'
import {
  getPropertyVerificationByUserId,
  getPropertyVerifyRefuseReason,
  cancelVerification,
  cancelBatchVerification
} from '@/utils/apiService'

const router = useRouter()
const activeMenu = ref('my-houses')
const activeIndex = ref('3')
const currentPage = ref(1)
const pageSize = ref(10)
const totalVerifications = ref(0)
const loading = ref(false)
const statusFilter = ref(null)
const selectedVerifications = ref([])

// 房产认证列表数据
const verificationList = ref([])

// 过滤后的认证列表
const filteredVerificationList = computed(() => {
  if (statusFilter.value === null) {
    return verificationList.value
  }
  return verificationList.value.filter(item => item.verifyStatus === statusFilter.value)
})

// 是否有可删除的项目
const hasDeleteableItems = computed(() => {
  return verificationList.value.some(item => canDelete(item.verifyStatus))
})

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已通过'
    case 2: return '已驳回'
    case 3: return '已取消'
    default: return '未知'
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 0: return 'warning'  // 待审核
    case 1: return 'success'  // 已通过
    case 2: return 'danger'   // 已驳回
    case 3: return 'info'     // 已取消
    default: return ''
  }
}

// 判断是否可以删除
const canDelete = (status) => {
  return status === 2 || status === 3  // 只有已驳回或已取消的可以删除
}

// 判断行是否可选择
const isRowSelectable = (row) => {
  return canDelete(row.verifyStatus)
}

// 菜单选择处理
const handleSelect = (key) => {
  switch (key) {
    case '1':
      router.push('/')
      break
    case '2':
      router.push('/house/search')
      break
    case '3':
      router.push('/house/publish')
      break
    case '4':
      router.push('/message')
      break
  }
}

// 用户命令处理
const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      ElMessage.success('退出登录成功')
      localStorage.removeItem('userEmail')
      localStorage.removeItem('isLoggedIn')
      router.push('/login')
      break
  }
}

// 获取用户房产认证数据
const fetchVerificationData = async () => {
  loading.value = true
  try {
    // 从localStorage获取用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (!userInfoStr) {
      ElMessage.error('未找到用户信息，请先登录')
      router.push('/login')
      return
    }

    const userInfo = JSON.parse(userInfoStr)
    const userId = userInfo.id

    if (!userId) {
      ElMessage.error('用户信息不完整，请重新登录')
      router.push('/login')
      return
    }

    // 调用API获取房产认证信息
    const response = await getPropertyVerificationByUserId(userId)

    if (response.data.code === '200') {
      verificationList.value = response.data.data || []
      totalVerifications.value = verificationList.value.length
      ElMessage.success(`加载了 ${verificationList.value.length} 条房产认证信息`)
    } else {
      ElMessage.error(response.data.message || '获取房产认证信息失败')
    }
  } catch (error) {
    console.error('获取房产认证信息失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  fetchVerificationData()
}

// 根据状态过滤
const filterByStatus = () => {
  // 过滤逻辑已在computed中实现
}

// 查看认证详情
const viewVerificationDetail = (verification) => {
  ElMessageBox.alert(`
    <div style="text-align: left;">
      <h3>房产认证详情</h3>
      <p><strong>认证ID：</strong>${verification.propertyVerifyId}</p>
      <p><strong>房产证编号：</strong>${verification.propertyNo}</p>
      <p><strong>房产地址：</strong>${verification.propertyAddr}</p>
      <p><strong>审核状态：</strong>${getStatusText(verification.verifyStatus)}</p>
      <p><strong>申请时间：</strong>${formatDateTime(verification.applyTime)}</p>
      ${verification.refuseReason ? `<p><strong>驳回原因：</strong>${verification.refuseReason}</p>` : ''}
    </div>
  `, '认证详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭'
  })
}

// 查看驳回原因
const viewRefuseReason = async (verification) => {
  try {
    // 如果本地已有驳回原因，直接显示
    if (verification.refuseReason && verification.refuseReason.trim()) {
      ElMessageBox.alert(verification.refuseReason, '驳回原因', {
        confirmButtonText: '知道了',
        type: 'warning'
      })
      return
    }

    // 如果本地没有驳回原因，尝试从后端获取
    if (verification.propertyNo) {
      ElMessage.info('正在获取驳回原因...')

      const response = await getPropertyVerifyRefuseReason(verification.propertyNo)

      if (response.data.code === '200' && response.data.data) {
        // 更新本地数据
        verification.refuseReason = response.data.data

        ElMessageBox.alert(response.data.data, '驳回原因', {
          confirmButtonText: '知道了',
          type: 'warning'
        })
      } else {
        ElMessage.warning('暂无驳回原因信息')
      }
    } else {
      ElMessage.warning('无法获取驳回原因：缺少房产证编号')
    }
  } catch (error) {
    console.error('获取驳回原因失败:', error)
    ElMessage.error('获取驳回原因失败，请稍后重试')
  }
}



// 删除单个认证
const deleteVerification = async (verification) => {
  if (!canDelete(verification.verifyStatus)) {
    ElMessage.warning('只能删除已驳回或已取消的房产认证')
    return
  }

  ElMessageBox.confirm(
      `确定要删除房产认证 ${verification.propertyNo} 吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      // 获取用户ID
      const userInfoStr = localStorage.getItem('userInfo')
      const userInfo = JSON.parse(userInfoStr)
      const userId = userInfo.id

      // 调用删除API
      const response = await cancelVerification(verification.propertyVerifyId, userId)

      if (response.data.code === '200') {
        ElMessage.success('房产认证删除成功')
        // 刷新数据
        await fetchVerificationData()
      } else {
        ElMessage.error(response.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除房产认证失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 批量删除认证
const batchDelete = async () => {
  if (selectedVerifications.value.length === 0) {
    ElMessage.warning('请选择要删除的房产认证')
    return
  }

  ElMessageBox.confirm(
      `确定要删除选中的 ${selectedVerifications.value.length} 条房产认证吗？此操作不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      // 获取用户ID
      const userInfoStr = localStorage.getItem('userInfo')
      const userInfo = JSON.parse(userInfoStr)
      const userId = userInfo.id

      // 获取选中的认证ID列表
      const propertyVerifyIds = selectedVerifications.value.map(item => item.propertyVerifyId)

      // 调用批量删除API
      const response = await cancelBatchVerification(propertyVerifyIds, userId)

      if (response.data.code === '200') {
        ElMessage.success(`成功删除 ${selectedVerifications.value.length} 条房产认证`)
        // 清空选择
        selectedVerifications.value = []
        // 刷新数据
        await fetchVerificationData()
      } else {
        ElMessage.error(response.data.message || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除房产认证失败:', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedVerifications.value = selection
}



const goToMyHouses = () => {
  router.push('/house/my-houses')
}

const goToAgentApply = () => {
  router.push('/agent/apply')
}

const goToAgentStatus = () => {
  router.push('/agent/status')
}

const goToAgentHouses = () => {
  router.push('/agent/houses')
}

const goToTenant = () => {
  router.push('/rental/tenant')
}

const goToLandlord = () => {
  router.push('/rental/landlord')
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const goToProfile = () => {
  router.push('/profile')
}


// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  // 重新获取数据（如果需要服务端分页）
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 重新获取数据（如果需要服务端分页）
}



// 页面加载时获取数据
onMounted(() => {
  fetchVerificationData()
})
</script>

<style scoped>
.my-houses-container {
  display: flex;
  min-height: 100vh;
  overflow: hidden;
  position: relative;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

/* 精美的动态背景 */
.dynamic-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #1a2980, #26d0ce);
  overflow: hidden;
}

/* 建筑物 */
.building {
  position: absolute;
  bottom: 0;
  background: rgba(30, 30, 50, 0.8);
  border-radius: 5px 5px 0 0;
  box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
}

.building-1 {
  left: 10%;
  width: 80px;
  height: 300px;
  animation: buildingGlow 4s infinite alternate;
}

.building-2 {
  left: 25%;
  width: 120px;
  height: 400px;
  animation: buildingGlow 5s infinite alternate-reverse;
}

.building-3 {
  left: 45%;
  width: 100px;
  height: 350px;
  animation: buildingGlow 6s infinite alternate;
}

.building-4 {
  left: 65%;
  width: 140px;
  height: 450px;
  animation: buildingGlow 4.5s infinite alternate-reverse;
}

.building-5 {
  left: 80%;
  width: 90px;
  height: 320px;
  animation: buildingGlow 5.5s infinite alternate;
}

@keyframes buildingGlow {
  0% {
    box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
  }
  100% {
    box-shadow: 0 -5px 25px rgba(100, 200, 255, 0.6);
  }
}

/* 云朵 */
.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  filter: blur(2px);
}

.cloud-1 {
  top: 20%;
  left: 5%;
  width: 80px;
  height: 30px;
  animation: cloudMove 25s linear infinite;
}

.cloud-2 {
  top: 35%;
  left: 70%;
  width: 120px;
  height: 40px;
  animation: cloudMove 30s linear infinite;
}

.cloud-3 {
  top: 15%;
  left: 40%;
  width: 100px;
  height: 35px;
  animation: cloudMove 35s linear infinite;
}

@keyframes cloudMove {
  0% {
    transform: translateX(-100px);
  }
  100% {
    transform: translateX(calc(100vw + 100px));
  }
}

/* 太阳 */
.sun {
  position: absolute;
  top: 80px;
  right: 100px;
  width: 80px;
  height: 80px;
  background: radial-gradient(circle, #ffeb3b, #ffc107);
  border-radius: 50%;
  box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  animation: sunPulse 3s infinite alternate;
}

@keyframes sunPulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  }
  100% {
    transform: scale(1.1);
    box-shadow: 0 0 60px #ff9800, 0 0 100px #ff5722;
  }
}

/* 光线 */
.light-ray {
  position: absolute;
  top: 120px;
  right: 140px;
  width: 400px;
  height: 200px;
  background: linear-gradient(to right, transparent, rgba(255, 235, 59, 0.2), transparent);
  transform-origin: left center;
  animation: rayRotate 10s infinite linear;
}

.ray-1 {
  transform: rotate(0deg);
  animation-delay: 0s;
}

.ray-2 {
  transform: rotate(60deg);
  animation-delay: 2s;
}

.ray-3 {
  transform: rotate(120deg);
  animation-delay: 4s;
}

@keyframes rayRotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 浮动装饰元素 */
.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 15s infinite linear;
}

.shape-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  left: -100px;
  animation-duration: 20s;
  background: radial-gradient(circle, rgba(74, 144, 226, 0.2) 0%, transparent 70%);
}

.shape-2 {
  width: 200px;
  height: 200px;
  bottom: -80px;
  right: -80px;
  animation-duration: 25s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 107, 107, 0.2) 0%, transparent 70%);
}

.shape-3 {
  width: 150px;
  height: 150px;
  top: 30%;
  right: 20%;
  animation-duration: 15s;
  background: radial-gradient(circle, rgba(80, 227, 194, 0.2) 0%, transparent 70%);
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-duration: 18s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 209, 102, 0.2) 0%, transparent 70%);
}

.shape-5 {
  width: 250px;
  height: 250px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-duration: 22s;
  background: radial-gradient(circle, rgba(155, 89, 182, 0.2) 0%, transparent 70%);
}

.shape-6 {
  width: 180px;
  height: 180px;
  top: 70%;
  left: 10%;
  animation-duration: 28s;
  background: radial-gradient(circle, rgba(231, 76, 60, 0.2) 0%, transparent 70%);
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(20px, 20px) rotate(90deg);
  }
  50% {
    transform: translate(0, 40px) rotate(180deg);
  }
  75% {
    transform: translate(-20px, 20px) rotate(270deg);
  }
  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.my-houses-wrapper {
  width: 100%;
  height: 100vh;
  z-index: 1;
  display: flex;
  flex-direction: column;
}

.top-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 30px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.app-title {
  color: white;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
}

.navbar-center {
  flex: 1;
  margin: 0 20px;
}

:deep(.el-menu--horizontal) {
  border: none;
  background: transparent !important;
}

:deep(.el-menu--horizontal .el-menu-item) {
  color: white;
  border: none;
}

:deep(.el-menu--horizontal .el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.2) !important;
}

:deep(.el-menu--horizontal .el-menu-item.is-active) {
  color: #4A90E2 !important;
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  color: white;
}

.username {
  font-size: 16px;
  font-weight: 500;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 250px;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  padding: 20px 0;
  height: 100%;
  box-shadow: 3px 0 10px rgba(0, 0, 0, 0.2);
}

.el-menu-vertical {
  border: none !important;
  height: 100%;
}

.el-menu-item,
.el-sub-menu__title {
  margin: 5px 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.el-menu-item:hover,
.el-sub-menu__title:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  overflow-y: auto;
  padding: 20px;
}

.content-header {
  margin-bottom: 30px;
}

.content-header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin: 0 0 10px;
}

.content-header p {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* 状态过滤器 */
.status-filter {
  display: flex;
  align-items: center;
  gap: 10px;
}

.verifications-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  flex: 1;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.section-header h3 {
  margin: 0;
  font-size: 24px;
  color: #2c3e50;
  font-weight: 700;
}

.verifications-container {
  padding: 20px;
}

/* 空状态样式 */
.empty-state {
  padding: 60px 20px;
  text-align: center;
}

:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-table__header th) {
  background-color: #f8f9fa;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

@media (max-width: 992px) {
  .sidebar {
    width: 80px;
  }

  .app-title,
  .el-menu-item span,
  .el-sub-menu__title span {
    display: none;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}
</style>
